package com.sxt.practiceapplication.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.sxt.practiceapplication.R;
import com.sxt.practiceapplication.databinding.LoadingBinding;
import com.sxt.practiceapplication.databinding.RefreshHeaderBinding;

import java.text.SimpleDateFormat;

import static com.sxt.practiceapplication.utils.DateUtils.getSystemTime;


public class RefreshListView extends ListView {

    private View pullDownRefreshView;

    private ImageView ivArrow;

    private LoadingBinding pbStatus;

    private TextView tvStatus;

    private TextView tvTime;

    private int pullDownRefreshHeight;

    /**
     * 下拉刷新
     */
    public static final int PULL_DOWN_REFRESH = 0;

    /**
     * 松手刷新
     */
    public static final int RELEASE_REFRESH = 1;

    /**
     * 正在刷新
     */
    public static final int REFRESHING = 2;

    /**
     * 当前状态
     */
    private int currentStatus = PULL_DOWN_REFRESH;

    private Animation upAnimation;

    private Animation downAnimation;

    private OnRefreshListener mOnRefreshListener;

    public RefreshListView(Context context) {
        this(context, null);
    }

    public RefreshListView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RefreshListView(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public RefreshListView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initHeaderView(context);
        initAnimation();
    }

    private void initAnimation() {
        upAnimation = new RotateAnimation(0, -180, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        upAnimation.setDuration(500);
        upAnimation.setFillAfter(true);

        downAnimation = new RotateAnimation(-180, -360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        downAnimation.setDuration(500);
        downAnimation.setFillAfter(true);
    }

    private void initHeaderView(Context context) {
        RefreshHeaderBinding headerBinding = RefreshHeaderBinding.inflate(LayoutInflater.from(context));
        LinearLayout headerView = headerBinding.getRoot();
        pullDownRefreshView = headerBinding.llPullDownRefresh;
        ivArrow = headerBinding.ivArrow;
        pbStatus = headerBinding.pbStatus;
        tvStatus = headerBinding.tvStatus;
        tvTime = headerBinding.tvTime;

        pullDownRefreshView.measure(0, 0);
        pullDownRefreshHeight = pullDownRefreshView.getMeasuredHeight();
        //默认隐藏下拉刷新控件
        pullDownRefreshView.setPadding(0, -pullDownRefreshHeight, 0, 0);

        this.addHeaderView(headerView);
    }

    private float startY = -1;

    private boolean needRefresh = false;

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        //到头部了
        //            getParent().requestDisallowInterceptTouchEvent(false);//放行
        //            getParent().requestDisallowInterceptTouchEvent(true);//拦截
        View child = getChildAt(0);
        needRefresh = getFirstVisiblePosition() == 0 && (child == null || child.getTop() == 0);
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //记录起始坐标
                startY = ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                if (startY == -1) {
                    startY = ev.getY();
                }
                if (currentStatus == REFRESHING) {
                    break;
                }
                //滑动得到新的坐标
                float endY = ev.getY();
                //计算滑动的距离
                float distanceY = endY - startY;
                if (distanceY > 0 && needRefresh) {//下拉
                    int paddingTop = (int) (-pullDownRefreshHeight + distanceY);
                    if (paddingTop < 0 && currentStatus != PULL_DOWN_REFRESH) {
                        currentStatus = PULL_DOWN_REFRESH;
                        refreshStatusView();
                    } else if (paddingTop > 0 && currentStatus != RELEASE_REFRESH) {
                        currentStatus = RELEASE_REFRESH;
                        refreshStatusView();
                    }
                    pullDownRefreshView.setPadding(0, paddingTop, 0, 0);
                }
                break;
            case MotionEvent.ACTION_UP:
                startY = -1;
                if (currentStatus == PULL_DOWN_REFRESH) {
                    pullDownRefreshView.setPadding(0, -pullDownRefreshHeight, 0, 0);
                } else if (currentStatus == RELEASE_REFRESH) {
                    currentStatus = REFRESHING;
                    refreshStatusView();
                    pullDownRefreshView.setPadding(0, 0, 0, 0);
                    if (mOnRefreshListener != null) {
                        mOnRefreshListener.onPullDownRefresh();
                    }
                }
                break;
        }
        performClick();
        return super.onTouchEvent(ev);
    }

    private void refreshStatusView() {
        switch (currentStatus) {
            case PULL_DOWN_REFRESH:
                ivArrow.startAnimation(downAnimation);
                tvStatus.setText("下拉刷新...");
                break;
            case RELEASE_REFRESH:
                ivArrow.startAnimation(upAnimation);
                tvStatus.setText("松手刷新...");
                break;
            case REFRESHING:
                tvStatus.setText("正在刷新...");
                pbStatus.getRoot().setVisibility(VISIBLE);
                ivArrow.clearAnimation();
                ivArrow.setVisibility(GONE);
                break;
        }
    }

    @Override
    public boolean performClick() {
        return super.performClick();
    }

    public void setOnRefreshListener(OnRefreshListener l) {
        this.mOnRefreshListener = l;
    }

    /**
     * 当数据请求完成后（成功或失败）的时候回调该方法
     *
     * @param success 请求是否成功
     */
    @SuppressLint("SetTextI18n")
    public void onRefreshFinish(boolean success) {
        tvStatus.setText("下拉刷新...");
        currentStatus = PULL_DOWN_REFRESH;
        ivArrow.clearAnimation();
        ivArrow.setVisibility(VISIBLE);
        pbStatus.getRoot().setVisibility(GONE);
        pullDownRefreshView.setPadding(0, -pullDownRefreshHeight, 0, 0);
        if (success) {
            tvTime.setText(getContext().getString(R.string.last_refresh_time) + getSystemTime());
        }

    }

    public interface OnRefreshListener {
        void onPullDownRefresh();
    }
}
